import React, { Component } from 'react';
import { Form, Row, Col, Input, message } from 'antd';
import request from '@sc/request';
const COUNT_DOWN_TIMES = 5;
const FormItem = Form.Item;

export default class LoginWithMsgFormItem extends Component {
  static defaultProps = {
    id: 'validCode',
    validField: 'account',
    disabled: false,
    focus: false,
    //默认获取手机验证码
    type: 'phone',

    // 发送短信类型,1=登录,2=注册,3=修改手机,4=忘记密码
    serviceType: 1,
  };

  constructor(props) {
    super(props);
    this.state = {
      time: 0,
    };

    this.codeInput = React.createRef();
  }

  mounted = true;
  getYCode = e => {
    e.preventDefault();
    const {
      form: { getFieldValue, validateFields },
      validField,
      type,
      serviceType,
    } = this.props;
    validateFields([validField], (err, values) => {
      if (!err) {
        let url;

        // TODO: 调用不同接口的时候接收的参数field也需要确认

        // 邮箱与手机调用不同的获取验证码接口
        if (type === 'phone') {
          url = '/ms/api/v1/uc/captcha';
        }
        // TODO: 邮箱接口还没
        if (type === 'email') {
          url = '/api/v1/ucenter/security/getPhoneCode';
        }
        console.log(validField, getFieldValue(validField));
        request(url, {
          method: 'get',
          data: {
            [validField]: getFieldValue(validField),
            type: serviceType,
          },
        })
          .then(res => {
            if (!this.mounted) return;
            if (res.code === 1) {
              this.setState({
                time: COUNT_DOWN_TIMES,
              });
              message.success(res.msg);
            } else {
              message.error(res.msg);
            }
          })
          .catch(err => {
            if (!this.mounted) return;
            message.error(`${err}`);
          });

        const timer = setInterval(() => {
          if (this.mounted && this.state.time > 0) {
            this.setState(({ time }) => ({ time: --time }));
          } else {
            clearInterval(timer);
          }
        }, 1000);
      }
    });
  };

  componentDidMount() {
    if (this.props.focus) this.codeInput.focus();
  }

  componentWillUnmount() {
    this.mounted = null;
  }

  render() {
    const {
      form: { getFieldDecorator },
      id,
      disabled,
    } = this.props;
    const { time } = this.state;
    const buttonDisabled = time !== 0 || disabled;
    return (
      <Row gutter={10}>
        <Col span={14}>
          <FormItem>
            {getFieldDecorator(id, {
              rules: [
                {
                  required: true,
                  message: '请输入验证码',
                },
                {
                  len: 6,
                  message: '请输入6位验证码',
                },
              ],
            })(
              <Input
                className="login-input"
                disabled={disabled}
                placeholder="请输入验证码"
                ref={ref => (this.codeInput = ref)}
              />
            )}
          </FormItem>
        </Col>
        <Col span={10}>
          <button
            className={`get-code ${buttonDisabled ? 'disabled' : ''}`}
            onClick={this.getYCode}
            disabled={buttonDisabled}
          >
            {time === 0 ? '发送' : `${time}后重新发送`}
          </button>
        </Col>
      </Row>
    );
  }
}
